<template>
  <div @touchmove.prevent>
    <Header v-show="false" :left="false" />
    <van-image
      ref="image"
      width="100%"
      fit
      :height="screenHight"
      src="assets/logo_back.png"
    />
    <div class="textScroll">
      <div style="width: 100%" align="center">
        <img src="assets/zl_logo_new2.png" style="width: 320px; height: 100px" />
      </div>

      <Form @submit="onSubmit" style="margin-top: 60px">
        <!-- <van-radio-group
          v-model="radio"
          style="margin: 17px 17px"
          direction="horizontal"
        >
          <van-icon color="#138087" size="large" name="setting" style="margin-right: 5px;margin-top: 3px;"/>
          <div style="margin-right: 10px">子系统</div>
          <van-radio name="1" shape="square"  checked-color="#138087">工作任务</van-radio>
          <van-radio name="2" shape="square"  checked-color="#138087">LPA检查</van-radio>
        </van-radio-group> -->
        <Field
          v-model="loginForm.username"
          left-icon="assets/userName.png"
          name="用户名"
          label="用户名"
          size="large"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <Field
          v-model="loginForm.password"
          left-icon="assets/password.png"
          name="密码"
          size="large"
          type="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-checkbox
          v-model="checked"
          checked-color="#138087"
          shape="square"
          style="margin: 15px 17px; font-style: oblique"
          >记住密码</van-checkbox
        >
        <div style="margin: 16px">
          <Row gutter="20">
            <!-- <Col span="12"> -->
            <Button round block type="info" color="#138087" native-type="submit"
              >登录</Button
            >
            <!-- </Col> -->
            <!-- <Col span="12">
              <Button round block type="warning" @click="setting">配置服务器地址</Button>
            </Col> -->
          </Row>
        </div>
      </Form>
      <!-- 图标位置 -->
      <Popup
        v-model="show"
        closeable
        close-icon-position="top-right"
        round
        position="bottom"
        :style="{ height: '30%' }"
      >
        <Cell-group title="设置服务器地址">
          <Field
            v-model="url"
            placeholder="服务器地址"
            clearable
            right-icon="scan"
            @click-right-icon="showScanner"
          />
        </Cell-group>
        <Button
          round
          block
          type="info"
          @click="storeSetting"
          size="normal"
          style="margin-top: 20px"
          >保存服务器地址</Button
        >
      </Popup>
    </div>
  </div>
</template>

<script>
import Header from "@/components/header.vue";
import apicloud from "@/libs/apicloud";
import {
  Form,
  Toast,
  Field,
  Button,
  Row,
  Col,
  Popup,
  CellGroup,
  Image as VanImage,
  Checkbox,
  RadioGroup,
  Radio,
  Icon,
} from "vant";
Vue.use(VanImage);
Vue.use(Checkbox);
Vue.use(Radio);
Vue.use(RadioGroup);
Vue.use(Icon);
import { _httpClient, bindAliasAndTags } from "@/libs/api";
//局域网内API地址
//import { _httpClientSIE } from "@/libs/apisie";

import { setToken, setBaseApiFrefix, getBaseApiFrefix } from "@/libs/auth";
import { registerUpdateLifecycle } from "echarts";
export default {
  name: "login",
  components: {
    Header,
    Form,
    Field,
    Button,
    Toast,
    Row,
    Col,
    Popup,
    CellGroup,
    Checkbox,
  },
  data() {
    return {
      radio: "1",
      checked: false,
      screenHight: 300, //屏幕高度
      loginForm: {
        username: "",
        password: "",
        loginType: "1",
      },
      url: "",
      show: false,
    };
  },
  created: function () {
    var td = api.require("talkingData");
    td.onPageStart({ pageName: "登录" });
    //alert("手机系统"+api.deviceName.toLowerCase());
    api.requestPermission(
      {
        list: ["camera", "microphone", "storage", "photos"],
      },
      function (ret, err) {}
    );

    try {
      var manageStorage = api.require("manageStorage");
      manageStorage.getDeviceVersion({}, function (rett) {
        if (Number(rett.version) >= 30) {
          manageStorage.hasAllFilePermission({}, function (ret) {
            if (ret.status == true) {
              return;
            } else {
              manageStorage.requestAllFilePermission({}, function (ret) {});
            }
          });
        } else {
          return;
        }
      });
    } catch {}


  },
  mounted() {
    //背景图片动态赋值
    this.screenHight = api.winHeight;
    //alert(api.getPrefs({sync: true,key: 'username'})  )
    //密码获取
    try {
      this.loginForm.username = api.getPrefs({ sync: true, key: "username" });
      this.loginForm.password = api.getPrefs({ sync: true, key: "password" });
      if (api.getPrefs({ sync: true, key: "username" }) != "") {
        this.checked = true;
      }
    } catch {
      //alert(123)
    }
    //双击返回键退出APP(only for android)
    var ci = 0;
    var time1, time2;
    this.$ac.addEventListener(
      {
        name: "keyback",
      },
      function (ret, err) {
        if (ci == 0) {
          time1 = new Date().getTime();
          ci = 1;
          api.toast({
            msg: "再按一次返回键退出",
          });
        } else if (ci == 1) {
          time2 = new Date().getTime();
          if (time2 - time1 < 3000) {
            api.closeWidget({
              id: api.appId,
              retData: {
                name: "closeWidget",
              },
              silent: true,
            });
          } else {
            ci = 0;
            api.toast({
              msg: "再按一次返回键退出",
            });
          }
        }
      }
    );
  },
  methods: {
    onSubmit(form) {
      this.userLogin({
        body: this.loginForm,
      });
    },
    storeSetting() {
      if (this.url) {
        setBaseApiFrefix(this.url);
        this.show = false;
      }
    },
    //打开扫描
    showScanner() {
      let _this = this;
      if (
        api.deviceName.toLowerCase() == "huawei" ||
        api.deviceName.toLowerCase() == "honor"
      ) {
        //_this.url = ret.result;

        var zyHmsScan = api.require("zyHmsScan");
        var param = {
          //returnAll:true
        };
        zyHmsScan.openDefaultView(param, function (ret) {
          //_this.addBarCode(ret.result);
          _this.url = ret.result;
          //api.alert({ msg: JSON.stringify(ret) });
        });

        // var QRScan = api.require("QRScan");
        // QRScan.customizedScanner(
        //   {
        //     rect: {
        //       x: 15, //（可选项）数字类型；模块左上角的 x 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       y: 0, //（可选项）数字类型；模块左上角的 y 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       w: 320, //（可选项）数字类型；模块的宽度；支持设置'auto'；默认：所属的 Window 或 Frame 的宽度
        //       h: 480, //（可选项）数字类型；模块的高度；支持设置'auto'；默认：所属的 Window 或 Frame 的高度
        //     },
        //     rectOfInterest: {
        //       x: 64, //（可选项）数字类型；扫码识别区域左上角的 x 坐标（相对于扫码区rect）；默认：0
        //       y: 65, //（可选项）数字类型；扫码识别区域左上角的 y 坐标（相对于扫码区rect）；默认：0
        //       w: 250, //（可选项）数字类型；扫码识别区域的宽度；默认：扫码区rect的宽度
        //       h: 250, //（可选项）数字类型；扫码识别区域的高度；默认：扫码区rect的高度
        //     },
        //     //tipString:'放入框内扫码',
        //     maskColor: "rgba(0,0,0,0.5)",
        //     scanLine: {
        //       color: "#00FF00",
        //       thickness: 2,
        //     },
        //     marginB: 30,
        //     formatType: "ALL",
        //   },
        //   function (ret) {
        //     if (ret) {
        //       _this.url = ret.result;
        //     }
        //   }
        // );
        //  QRScan.closeCustomizedScanner();
      } else {
        var FNScanner = this.$ac.require("FNScanner");
        FNScanner.openScanner(
          {
            autorotation: true,
          },
          function (ret, err) {
            if (ret) {
              if (ret.eventType == "success" && ret.content != "") {
                _this.url = ret.content;
              }
            } else {
              alert(JSON.stringify(err));
            }
          }
        );
      }
    },
    setting() {
      this.show = true;
      this.url = getBaseApiFrefix();
    },
    async encryption(str) {
      var encStr = encodeURIComponent(str);
      encStr = btoa(encStr);
      return encStr;
    },
    async userLogin(data) {
      if (data.username == "TMSCPMCadmin") {
        Toast.clear();
        Toast.fail("请不要用管理员账户登录！");
        return;
      }
      //Toast.success(_httpClient.getApiPrefix() + "/login");
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等...",
      });

      try {
        // var s1=data.body.username;
        // var s2=data.body.password;
        // var encStr =encodeURIComponent(data.body.username)
        // encStr = btoa(encStr);
        // var encStr1 =encodeURIComponent(data.body.password)
        // encStr1 = btoa(encStr1);
        // data.body.username=encStr;
        // data.body.password=encStr1;
        let res = await _httpClient.postWithoutTkn(
          _httpClient.getApiPrefix() + "/login",
          data
        );
        if (res.code === 200) {
          //记住密码
          if (this.checked == true) {
            try {
              api.setPrefs({ key: "username", value: data.body.username });
              api.setPrefs({ key: "password", value: data.body.password });
            } catch (e) {
              alert(e);
            }
          } else {
            api.setPrefs({ key: "username", value: "" });
            api.setPrefs({ key: "password", value: "" });
          }
          Toast.success(res.msg);
          setToken(res.token);
          //绑定极光推送
          bindAliasAndTags(data.body.username);
          this.$ac.sendEvent({
            name: "loginSuccess",
          });

          // this.$ac.closeWin()
          this.$ac.closeToWin({
            name: "root",
          });
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
        //Toast.fail("123");
      }
    },
  },
};
</script>

<style>
.login {
  background: "../../assets/20200605100824.png";
}

.textScroll {
  display: inline-block;
  position: fixed;
  top: 10rem;
  bottom: 5px;
  overflow: scroll;
  right: 0;
  width: 100%;
  margin-bottom: 4.7rem;
  z-index: 1;
}
</style>
